/**
 * 报表设计公司(2011)
 */
package com.reportgear.report.view.grid.util;

import java.awt.Color;
import java.awt.Image;
import java.awt.image.PixelGrabber;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Properties;

/**
 * 实用类
 * 
 * @version 1.0 2011-3-24
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since ANNCSR 2.0
 */
public class Utils {
    public static char FileNameInvalidChars[] = { '"', '\'', '[', ']', '\\', '/', ':', '*', '?', '<', '>', '|' };
    private static Properties prop = null;

    private Utils() {
    }

    public static String doubleToString(double d) {
        return convertNumberStringToString(String.valueOf(d));
    }

    public static String convertNumberStringToString(String s) {
        int i = s.indexOf('.');
        if (i < 0) {
            return s;
        }
        int j = s.indexOf('E');
        if ((i == 1) && (j > 0)) {
            String s1 = s.substring(0, j);
            StringBuffer stringbuffer = new StringBuffer(s1.substring(2));
            stringbuffer.insert(0, s1.charAt(0));
            String s3 = s.substring(j + 1);
            if (s3.startsWith("+")) {
                s3 = s3.substring(1);
            }
            int l = Integer.parseInt(s3);
            if (l <= 0) {
                if (stringbuffer.charAt(stringbuffer.length() - 1) == '0') {
                    stringbuffer.deleteCharAt(stringbuffer.length() - 1);
                }
                for (int i1 = 0; i1 < -l; i1++) {
                    stringbuffer.insert(0, "0");
                }

                stringbuffer.insert(1, ".");
            } else if (stringbuffer.length() > l + 1) {
                stringbuffer.insert(l + 1, '.');
            } else {
                for (; stringbuffer.length() < l + 1; stringbuffer.append("0")) {
                }
            }
            return stringbuffer.toString();
        }
        String s2 = s.substring(i + 1);
        int k;
        if ((k = s2.indexOf("9999")) >= 0) {
            double d = Double.parseDouble(s);
            if (k == 0) {
                return Long.toString(Math.round(d));
            }
            if (Math.abs(d) > 9.2233720368547758E+018D) {
                String s4 = Double.toString(d);
                int j1 = s4.indexOf(".");
                if ((j1 > 0) && (s4.length() - j1 - 1 > k)) {
                    s4 = s4.substring(0, j1 + k + 1);
                }
                if (s4.endsWith(".0")) {
                    return s4.substring(0, s4.length() - 2);
                } else {
                    return s4;
                }
            }
            String s5 = d >= 0.0D ? "" : "-";
            long l1 = (long) Math.pow(10D, k - 1);
            long l2 = l1 * 10L;
            d = Math.abs(d);
            long l3 = Math.round(d * l2);
            String s6 = s5 + Long.toString(l3 / l2);
            long l4 = l2 != 0L ? l3 % l2 : 0L;
            if (l4 < 0L) {
                return s;
            }
            if (l4 == 0L) {
                StringBuffer stringbuffer1 = new StringBuffer("");
                for (int k1 = k; k1 > 0; k1--) {
                    stringbuffer1.insert(0, "0");
                }

                return s6 + "." + stringbuffer1;
            }
            StringBuffer stringbuffer2 = new StringBuffer(Long.toString(l4));
            while (l4 < l1) {
                l4 *= 10L;
                stringbuffer2.insert(0, "0");
            }
            return s6 + "." + stringbuffer2;
        }
        if ((k = s2.indexOf("0000")) >= 0) {
            s = s.substring(0, i + Math.max(k, 1) + 1);
        }
        if (s.endsWith(".0")) {
            s = s.substring(0, s.length() - 2);
        }
        return s;
    }

    public static String inputStreamToString(InputStream inputstream) {
        BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(inputstream));
        StringBuffer stringbuffer = new StringBuffer();
        try {
            for (String s = ""; (s = bufferedreader.readLine()) != null;) {
                stringbuffer.append(s);
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return stringbuffer.toString();
    }

    public static Number objectToNumber(Object obj) {
        if (obj == null) {
            return new Integer(0);
        }
        if (obj instanceof Number) {
            return ((Number) obj);
        }
        String str = objectToString(obj);
        try {
            return Double.valueOf(str);
        } catch (NumberFormatException ex) {
        }
        return new Integer(0);
    }

    /**
     * 对象转化为字符串
     * 
     * @param o
     *            对象
     * @return 对象字符串
     */
    public static String objectToString(Object o) {
        if (o == null) {
            o = "";
        }
        if (o instanceof Number) {
            return convertNumberStringToString(o.toString());
        }
        if (o instanceof Date) {
            // DefaultValues defaultvalues = FRContext.getDefaultValues();
            // if (obj instanceof Time) {
            // return defaultvalues.getTimeFormat().format(obj);
            // }
            // if (obj instanceof Timestamp) {
            // return defaultvalues.getDateTimeFormat().format(obj);
            // } else {
            // return defaultvalues.getDateFormat().format(obj);
            // }
        }
        if ((o instanceof Image))// || (obj instanceof UploadedImage)) {
        {
            return "";

        } else {
            return o.toString();
        }
    }

    public static Color getXORColor(Color color) {
        if (color == null) {
            return null;
        } else {
            return new Color(255 - color.getRed(), 255 - color.getGreen(), 255 - color.getBlue());
        }

    }

    public static int filterRGB(int i, int j) {
        int k = (int) ((0.29999999999999999D * (i >> 16 & 0xff) + 0.58999999999999997D * (i >> 8 & 0xff) + 0.11D * (i & 0xff)) / 3D);
        k = 255 - ((255 - k) * (100 - j)) / 100;
        if (k < 0) {
            k = 0;
        }

        if (k > 255) {
            k = 255;
        }

        return i & 0xff000000 | k << 16 | k << 8 | k;
    }

    public static String[] splitString(String s, char c) {
        return splitString(s, "" + c);
    }

    public static String[] splitString(String s, String s1) {
        if ((s == null) || (s.length() == 0)) {
            return new String[0];
        } else {
            return s.split("\\Q" + s1 + "\\E");
        }

    }

    public static int[] splitStringToIntArray(String s, String s1) {
        String as[] = splitString(s, s1);
        int ai[] = new int[as.length];
        for (int i = 0; i < as.length; i++) {
            try {
                ai[i] = Integer.parseInt(as[i]);
            } catch (NumberFormatException numberformatexception) {
            }
        }

        return ai;
    }

    public static void swap(java.util.List list, int i, int j) {
        Object obj = list.get(i);
        list.set(i, list.get(j));
        list.set(j, obj);
    }

    public static String replaceAllString(String s, String as[], String as1[]) {
        for (int i = 0; i < as.length; i++) {
            s = replaceAllString(s, as[i], as1[i]);
        }

        return s;
    }

    public static String replaceAllString(String s, String s1, String s2) {
        if (s == null) {
            return null;
        } else {
            return s.replaceAll("\\Q" + s1 + "\\E", s2);
        }

    }

    public static void copyBinaryTo(File file, OutputStream outputstream) throws IOException {
        copyBinaryTo(((new FileInputStream(file))), outputstream);
    }

    public static void copyBinaryTo(InputStream inputstream, OutputStream outputstream) throws IOException {
        byte abyte0[] = new byte[10240];
        int i;
        while ((i = inputstream.read(abyte0)) >= 0) {
            outputstream.write(abyte0, 0, i);
        }

        outputstream.flush();
    }

    public static void copyCharTo(Reader reader, Writer writer) throws IOException {
        if (System.getProperty("java.vendor").toUpperCase().startsWith("IBM")) {
            char ac[] = new char[10240];
            int i;
            while ((i = reader.read(ac)) >= 0) {
                writer.write(ac, 0, i);
            }

            writer.flush();
        } else {
            BufferedReader bufferedreader = new BufferedReader(reader);
            PrintWriter printwriter = new PrintWriter(writer);
            String s;

            for (int j = 0; (s = bufferedreader.readLine()) != null; j++) {
                if (j > 0) {
                    printwriter.println();
                }

                printwriter.print(s);
            }

            printwriter.flush();
            printwriter.close();
            bufferedreader.close();
        }

    }

    public static int[] grabImagePixelsArray(Image image, int i, int j) {
        int ai[] = new int[i * j];
        PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, i, j, ai, 0, i);
        try {
            pixelgrabber.grabPixels();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

        return ai;
    }

    public static boolean mkdirs(File file) {
        if (!file.exists()) {
            return file.mkdirs();
        } else {
            return true;
        }

    }

    public static boolean mkfile(File file) throws IOException {
        if (file == null) {
            return false;
        }

        if (file.exists()) {
            return true;
        } else {
            mkdirs(file.getParentFile());
            file.createNewFile();
            return true;
        }

    }

    public static String javaColorToCSSColor(Color color) {
        StringBuffer stringbuffer = new StringBuffer("rgb(");
        stringbuffer.append(color.getRed());
        stringbuffer.append(",");
        stringbuffer.append(color.getGreen());
        stringbuffer.append(",");
        stringbuffer.append(color.getBlue());
        stringbuffer.append(")");
        return stringbuffer.toString();
    }

    public static boolean isFileNameInvalidChar(char c) {
        for (char fileNameInvalidChar : FileNameInvalidChars) {
            if (c == fileNameInvalidChar) {
                return true;
            }

        }

        return false;
    }

    public static boolean deleteFile(File file) {
        if ((file == null) || !file.exists()) {
            return false;
        }

        if (file.isDirectory()) {
            File afile[] = file.listFiles();
            for (int i = 0; i < afile.length; i++) {
                if (!deleteFile(afile[i])) {
                    return false;
                }

            }

        }
        return file.delete();
    }

    public static String createWhiteSpaceString(int i) {
        StringBuffer stringbuffer = new StringBuffer();
        for (int j = 0; j < i; j++) {
            stringbuffer.append(" ");
        }

        return stringbuffer.toString();
    }

    public static Method getDeclaredMethod(Class paramClass, String paramString, Class[] paramArrayOfClass) {
        try {
            return paramClass.getDeclaredMethod(paramString, paramArrayOfClass);
        } catch (NoSuchMethodException localNoSuchMethodException) {
            paramClass = paramClass.getSuperclass();
            if (paramClass != null) {
                return getDeclaredMethod(paramClass, paramString, paramArrayOfClass);
            }

        }
        return null;
    }

    public static Field getDeclaredField(Class paramClass, String paramString) {
        try {
            return paramClass.getDeclaredField(paramString);
        } catch (NoSuchFieldException localNoSuchFieldException) {
            paramClass = paramClass.getSuperclass();
            if (paramClass != null) {
                return getDeclaredField(paramClass, paramString);
            }

        }
        return null;
    }

    public static boolean classInstanceOf(Class class1, Class class2) {
        if ((class1 == null) || (class2 == null)) {
            return false;
        }

        if (class1.equals(class2)) {
            return true;
        }

        Class aclass[] = class1.getInterfaces();
        if (aclass != null) {
            for (Class aclas : aclass) {
                if (classInstanceOf(aclas, class2)) {
                    return true;
                }

            }

        }
        return classInstanceOf(class1.getSuperclass(), class2);
    }

    public static byte[] objectToByte(Object obj) {
        byte abyte0[] = new byte[0];
        try {
            ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
            ObjectOutputStream objectoutputstream = new ObjectOutputStream(bytearrayoutputstream);
            objectoutputstream.writeObject(obj);
            abyte0 = bytearrayoutputstream.toByteArray();
            bytearrayoutputstream.close();
            objectoutputstream.close();
        } catch (Exception exception) {
            System.out.println("translation" + exception.getMessage());
            exception.printStackTrace();
        }

        return abyte0;
    }

    public static String getInstallHome() {
        // String s = System.getProperty(Consts.APP_NAME + "_HOME");
        // if (!(new File(s + File.separator + "lib")).exists()) {
        // s = "D:\\FineReport\\develop\\code\\engine\\";
        // }

        return "s";
    }

    public static Properties getSystemEnvs() throws Exception {
        if (prop == null) {
            prop = new Properties();
        } else {
            return prop;
        }

        Process process = null;
        // if (OperatingSystem.isWindows()) {
        // process = Runtime.getRuntime().exec("cmd /c set");
        // } else {
        // return prop;
        // }

        BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        do {
            String s;
            if ((s = bufferedreader.readLine()) == null) {
                break;
            }

            int i = s.indexOf("=");
            if (i > -1) {
                String s1 = s.substring(0, i);
                String s2 = s.substring(i + 1);
                prop.setProperty(s1, s2);
            }

        } while (true);
        return prop;
    }
}
